<?php

// +----------------------------------------------
// | Name: 星空框架 管理员模型
// +----------------------------------------------
// | Version: V5.0
// +----------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +----------------------------------------------
// | Time: 2021-04-21 15:44
// +----------------------------------------------
declare(strict_types=1);

namespace app\common\model;

use think\facade\Session;
use think\model\concern\SoftDelete;

/**
 * @xk 管理员模型
 */
class Admin extends BaseModel
{
    use SoftDelete;
    protected $name = 'admin';
    protected $pk = 'admin_id';
    protected $deleteTime = 'delete_time';

    /**
     * @xk 写入前操作
     *
     * @method onBeforeWrite
     *
     * @param [type] $data [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-21T15:46:08+080
     */
    public static function onBeforeWrite($data)
    {
        unset($data['act']);
        unset($data['controllers']);
        unset($data['actions']);
        if (!$data->create_time) {
            $data->update_time = $data->create_time = date('Y-m-d H:i:s');
        }
        $data->update_time = date('Y-m-d H:i:s'); // 操作时间 实际发布时间
        $admin_pass = isset($data['admin_pass']) ? $data['admin_pass'] : '';
        unset($data['admin_pass']);
        $admin_pass1 = isset($data['admin_pass1']) ? $data['admin_pass1'] : '';
        unset($data['admin_pass1']);

        if ('' != $admin_pass && '' != $admin_pass1 && $admin_pass == $admin_pass1) {
            $data->pass_key = self::getCodeNo('xk', 8, 5);
            $data->admin_pass = makePass($admin_pass, $data->pass_key);
        }
    }

    /**
     * @xk 检测登录控制
     *
     * @method checkLogin
     *
     * @param [type] $data [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-19T10:22:26+080
     */
    public static function checkLogin($data)
    {
        //检测验证码
        $captcha = isset($data['captcha']) ? $data['captcha'] : '';
        $hasCaptch = Session::get('captcha');
        if (!captcha_check($captcha)) {
            return ['result_code' => 404, 'result_msg' => '验证码不正确或已经失效', 'backUrl' => ''];
        }
        $admin_num = $data['admin_num'];
        $admin_pass = $data['admin_pass'];
        if($admin_num == config('manage.suppler_admin_num')){
          $admin_info = self::onlyTrashed()->where(['admin_num' => $admin_num])
                        ->field('`admin_id`,`admin_name`,`head_pic`,`admin_pass`,`pass_key`,`status`,`admin_group_id`')
                        ->find();
        }else{
          $admin_info = self::where(['admin_num' => $admin_num])
                        ->field('`admin_id`,`admin_name`,`head_pic`,`admin_pass`,`pass_key`,`status`,`admin_group_id`')
                        ->find();
        }

        if (!$admin_info) {
            return ['result_code' => 404, 'result_msg' => '当前登录账号不存在，请联系管理员处理', 'backUrl' => ''];
        }
        switch ($admin_info['status']) {
        case '0':
          return ['result_code' => 404, 'result_msg' => '当前账号未通过审核', 'backUrl' => ''];
          break;

        default:
          // 开始校验角色 是否有效
          $adminGroupModel = new AdminGroup();
          $admin_group_info = $adminGroupModel
                              ->field('`status`,`auth_rule_id`')
                              ->find($admin_info['admin_group_id']); //角色信息
          if (!$admin_group_info) {
              return ['result_code' => 404, 'result_msg' => '账户所属管理组不存在，请联系超级管理员处理', 'backUrl' => ''];
          }
          if (1 != $admin_group_info['status']) {
              return ['result_code' => 404, 'result_msg' => '账户管理组已经被停用，请联系超级管理员处理', 'backUrl' => ''];
          }
          $has_pass = makePass($admin_pass, $admin_info['pass_key']);
        //   dump($admin_info);
        //   var_dump($has_pass);
        //   dump($admin_info['pass_key']);die;
          if ($admin_info['admin_pass'] != $has_pass) {
              return ['result_code' => 404, 'result_msg' => '登录账号密码错误，请重试', 'backUrl' => ''];
          }

          // 写入登录信息
          $now_ip = getRealIP();
          $admin_data = [];
          $admin_data['login_ip'] = getRealIP();
          $admin_data['admin_id'] = $admin_info['admin_id'];
          $admin_data['login_time'] = date('Y-m-d H:i:s');
          $admin_data['auth_token'] = makePass($admin_num.$now_ip,'20240304');
          if($admin_num == config('manage.suppler_admin_num')){
            self::onlyTrashed()->find($admin_info['admin_id'])->restore();
            self::where([['admin_id','=',$admin_info['admin_id']]])->save($admin_data);
            self::destroy($admin_info['admin_id']);
          }else{
            self::find($admin_info['admin_id'])->save($admin_data);
          }
          $admin_info['head_pic'] = getShowUrl($admin_info['head_pic']);
          $auth_key = $admin_data['auth_token'];
          Session::set('auth_key',$auth_key);
          Session::set('admin_num', $admin_num);
          Session::set('admin_info', $admin_info);
          Session::set('auth_rule_id', $admin_group_info['auth_rule_id']); // 角色允许的权限节点id
          Session::set('admin_id', $admin_info['admin_id']);
          Session::set('admin_group_id', $admin_info['admin_group_id']); //权限ID 写入
          $backUrl = '/'.config('manage.manage_name').'/'.config('manage.version');
          return ['result_code' => 200, 'result_msg' => '登录成功', 'backUrl' => $backUrl];
          break;
      }
    }
}
